<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="is--card">
      <template #form="{ form }">
        <VGroup>
          <el-select class="selectClass !w-[140px]" v-model="form.skuRange.type">
            <el-option
              v-for="item in skuOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-input
            v-model="form.skuRange.value"
            placeholder="SKU"
            :autosize="{ minRows: 1, maxRows: 2 }"
            class="w-40"
            type="textarea"
          />
        </VGroup>
        <VGroup>
          <el-select class="selectClass !w-[120px]" v-model="form.personRange.type">
            <el-option
              v-for="item in personOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <select-personnel
            class="w-40"
            v-model="form.personRange.value"
            :multiple="true"
          ></select-personnel>
        </VGroup>
        <el-select class="!w-[160px]" v-model="form.change_type" placeholder="变更类型">
          <el-option
            v-for="item in changetypeOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <SelectSupplieQuery
          v-model="form.supplier_id"
          placeholder="供应商"
        ></SelectSupplieQuery>
        <VGroup>
          <el-select class="selectClass !w-[120px]" v-model="form.timeRange.type">
            <el-option
              v-for="item in timeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-date-picker
            v-model="form.timeRange.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="max-width: 300px"
            :default-time="defaultTime()"
          />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <div v-if="tabsLoad" class="w-full">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane
              :label="item.status_text"
              :name="item.status"
              v-for="(item, index) in tabList"
              :key="index"
            >
              <template #label>
                {{ item.status_text }}(<span
                  :class="
                    activeName == item.status ? 'base-text-color' : 'text-[#999999]'
                  "
                  >{{ item.count }}</span
                >)
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
        <VButton
          auth="/goods/goods-management/change-order/check"
          type="primary"
          @click="handleCheck"
          >审核</VButton
        >
        <VButton auth="/goods/goods-management/change-order/cancel" @click="handleCancel"
          >取消</VButton
        >
      </template>
    </VTable>
  </VPage>
  <AuditModel v-model="auditVisible" @submit="auditSubmit" />
  <ChangeDetail ref="ChangeDetailRef"></ChangeDetail>
  <AuditRecord ref="AuditRecordRef"></AuditRecord>
</template>

<script setup name="Goods-managementChange-order" lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, check } from "./api/index.js";
import AuditModel from "@/components/AuditModel/index.vue";
import { skuOption, personOption, timeOption, changetypeOption } from "./data.js";
import ChangeDetail from "./components/ChangeDetail.vue";
import SelectSupplieQuery from "@/components/Selects/SelectSupplieQuery/index.vue";
import AuditRecord from "./components/AuditRecord.vue";

const tableRef = ref();
const activeName = ref("");
// const tabList = ref([]);

const data = reactive({
  tabList: [],
  tabsLoad: false,
});
const { tabList, tabsLoad } = toRefs(data);

const tableOptins = reactive({
  rowConfig: { height: 150 },
  showHeaderOverflow: true,
  showOverflow: true,
  formConfig: {
    data: {
      check_status: "",
      skuRange: { type: "sku", value: "", range: false },
      personRange: { type: "apply_user_id", value: "", range: false },
      timeRange: { type: "apply_time", value: "", range: false },
    },
  },
  columns: [
    { type: "checkbox", width: "40" },
    {
      field: "change_number",
      title: "商品资料变更单",
      width: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class={`check_status${row.check_status}`}>{row.check_status_text}</div>
              <div>{row.change_number}</div>
            </div>
          );
        },
      },
    },
    {
      field: "goods_change_order_detail",
      title: "变更详情",
      minWidth: "260",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex justify-between mb-2">
                <div>变更SKU数：{row.goods_change_order_detail?.length}</div>
                <el-button
                  type="primary"
                  link
                  onClick={() => {
                    handleViewDetail(row);
                  }}
                >
                  查看详情
                </el-button>
              </div>
              {row.goods_change_order_detail.slice(0, 2).map((item, index) => {
                return (
                  <div class="border px-1 py-1">
                    <div>
                      <vText title="SKU" value={item.sku_text?.sku}></vText>
                    </div>
                    <div>
                      <vText title="产品名称" value={item.sku_text?.sku_cn_title}></vText>
                    </div>
                  </div>
                );
              })}
            </div>
          );
        },
      },
    },
    {
      field: "goods_change_order_detail",
      title: "变更内容",
      minWidth: "350",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.goods_change_order_detail.map((item, index) => {
                return (
                  <div key={index}>
                    <div>
                      <span>{item?.goods_sku?.sku || "-"}</span>
                      <span v-html={item.content}></span>
                    </div>
                  </div>
                );
              })}
            </div>
          );
        },
      },
    },
    {
      field: "check_status_text",
      title: "飞书审核节点",
      width: "120",
      slots: {
        default: ({ row }) => {
          return (
            <el-button type="primary" link onClick={() => handleAuditRecord(row)}>
              审核记录
            </el-button>
          );
        },
      },
    },
    { field: "change_type_text", title: "变更类型", width: "120" },
    {
      title: "备注",
      minWidth: "180",
      field: "apply_remark",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="申请备注" value={row.apply_remark}></VText>
              <VText title="审核备注" value={row.check_remark}></VText>
            </div>
          );
        },
      },
    },
    {
      title: "申请人",
      minWidth: "180",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="申请人" value={row.apply_user_id_text}></VText>
              <VText title="申请时间" value={row.apply_time}></VText>
            </div>
          );
        },
      },
    },
    {
      title: "审核人",
      minWidth: "180",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="审核人" value={row.check_user_id_text}></VText>
              <VText title="审核时间" value={row.check_time}></VText>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: async ({ page, form }) => {
        const { apply_time, check_time } = form || {};
        let formData = {
          ...form,
          apply_time_start: apply_time?.[0] || undefined,
          apply_time_end: apply_time?.[1] || undefined,
          check_time_start: check_time?.[0] || undefined,
          check_time_end: check_time?.[1] || undefined,
          apply_time: undefined,
          check_time: undefined,
        };
        const res = await getList({ ...formData, ...page });

        getCount(res?.data?.count);
        // nextTick(() => {
        //   tabList.value = res?.data?.count || [];
        // });
        return new Promise(function (resolve) {
          resolve({
            data: res.data.list,
            total: res.total,
          });
        });
      },
    },
  },
});

const getCount = (countList) => {
  tabList.value = countList;
  nextTick(() => {
    tabsLoad.value = false; // 先隐藏 teleport 内容
    nextTick(() => {
      tabsLoad.value = true; // 再重新显示
    });
  });
};

//审核
const auditVisible = ref(false);
const auditIds = ref([]);
const handleCheck = () => {
  const records = tableRef?.value.$table.getCheckboxRecords();
  if (records?.length == 0) {
    return ElMessage.warning("请至少选择一条数据!");
  }
  const ids = records.map((item) => item.id);
  auditIds.value = ids;
  auditVisible.value = true;
};
const auditSubmit = async (data) => {
  const { operation, remark } = data;
  if (!operation) {
    return ElMessage.warning("请选择审核状态!");
  }
  const params = {
    change_id: auditIds.value,
    operation,
    remark,
  };
  try {
    const { code, message } = await check(params);
    if (code != 200) {
      return;
    }
    ElMessage.success(message);
    auditVisible.value = false;
    refresh();
  } catch (error) {}
};
//取消
const handleCancel = () => {
  const records = tableRef?.value.$table.getCheckboxRecords();
  if (records?.length == 0) {
    return ElMessage.warning("请至少选择一条数据!");
  }
  const ids = records.map((item) => item.id);
  ElMessageBox.confirm("确定取消吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const { code, message } = await check({ change_id: ids, operation: 3 });
      if (code != 200) {
        return;
      }
      ElMessage.success(message);
      refresh();
    } catch (error) {}
  });
};

const handleClick = (val) => {
  const form = tableRef.value.getForm();
  tableRef.value.setForm({
    ...form,
    check_status: val.props.name.toString(),
  });
  // tableRef.value.setForm({
  //   check_status: val.props.name.toString(),

  // });
  refresh();
};
//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

const ChangeDetailRef = ref();
const handleViewDetail = (obj) => {
  ChangeDetailRef.value.open(obj);
};

const AuditRecordRef = ref();
const handleAuditRecord = (row) => {
  AuditRecordRef.value.open(row.id);
};
</script>
<style lang="scss">
//审核通过
.check_status0 {
  color: #3366f1;
  background: rgba(51, 102, 241, 0.1);
  display: inline-block;
  padding: 2px 4px;
}

.check_status1 {
  color: #00ac76;
  background: rgba(0, 172, 118, 0.2);
  display: inline-block;
  padding: 2px 4px;
}

//审核未通过
.check_status2 {
  color: #ff0000;
  background: rgba(229, 1, 19, 0.2);
  display: inline-block;
  padding: 2px 4px;
}

//审核失败
.check_status3 {
  color: #6c7283;
  background-color: rgba(108, 114, 131, 0.2);
  display: inline-block;
  padding: 2px 4px;
}
</style>
<style lang="scss" scoped>
.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}
</style>
